# build in python3.5.2
# 作者：陈常鸿
# 使用tensorflow去分析比特币价格和交易
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

path_amount='F:/btc_price_history/btc_amount_nd.txt'
path_rate='F:/btc_price_history/btc_rate_nd.txt'
rate=np.loadtxt(path_rate,delimiter=',')
amount=np.loadtxt(path_amount,delimiter=',')

iteration=1000
learning_rate=0.1

samples=rate.shape[0]

x=tf.placeholder("float")
y=tf.placeholder("float")

w=tf.Variable(0.0,name='weight')
b=tf.Variable(0.0,name='bais')

pred=tf.add(tf.multiply(x,w),b)
cost=tf.reduce_sum(tf.pow(pred-y,2))/(2*samples)

optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
init=tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for i in range(iteration):
        for (X,Y) in zip(rate,amount):
            sess.run(optimizer,feed_dict={x:X,y:Y})

        if (i+1) % 50==0:
            c=sess.run(cost,feed_dict={x:rate,y:amount})
            print('集数：','%04d'%(i+1),'代价函数：','{:.9f}'.format(c),'权重=',sess.run(w),'偏差=',sess.run(b))

    training_cost=sess.run(cost,feed_dict={x:rate,y:amount})

    plt.plot(amount,rate,'ro',label='original data')
    plt.plot(sess.run(w)*rate+sess.run(b),rate,label='fix line')
    plt.legend()
    plt.show()
